/*!
 * Drag javaScript 2016
  
 * Author : ChenYang
 * Date   : 2016-02-19
 * Address: ShangHai,China
 */


/*
 * drag  : 拖拽
 * obj   : 当前对象
 */

function drag(obj, JSON) {

    var disX = 0;
    var disY = 0;
    var Config = {
        iType: 0, //left and top
        scope: document,
        sCon: null,
        isScrollBar: {
            bStatus: false,
            dir: 'y'
        },

        xMin: 0, //x方向最小值
        xMax: obj.parentNode.offsetWidth - obj.offsetWidth, //x方向最大值
        yMin: 0, //y方向最小值
        yMax: obj.parentNode.offsetHeight - obj.offsetHeight, //y方向最大值
        callback:null
    }



    Cy._extend(Config,JSON,true);

    //console.log( Config )

    obj.onmousedown = function(e) {

        var ev = e || window.event;
        var self = this;
        disX = ev.clientX - this.offsetLeft;
        disY = ev.clientY - this.offsetTop;

        Config.scope.onmousemove = function(e) {

            var ev = e || window.event;

            var l = ev.clientX - disX;
            var t = ev.clientY - disY;

            if (Config.iType === 0) { //x、y均可拖拽

                l = Cy._range(Config.xMin, Config.xMax, l); //left
                t = Cy._range(Config.yMin, Config.yMax, t); //top

                self.style.left = l + "px";
                self.style.top = t + "px";
                if(Config.callback) Config.callback(l,t);
            }
            if (Config.iType === 1) { //x方向可拖拽


                l = Cy._range(Config.xMin, Config.xMax, l); //left
                self.style.left = l + "px";

                //是否为滚动条X
                if (Config.isScrollBar.bStatus && Config.isScrollBar.dir === 'x') { // 带滚动区域
                    scale = l / Config.xMax;
                    Config.sCon.style.left = -scale * (Config.sCon.offsetWidth - Config.sCon.parentNode.offsetWidth) + "px";
                }
                if(Config.callback) Config.callback(l);
            }
            if (Config.iType === 2) { //y方向可拖拽

                t = Cy._range(Config.yMin, Config.yMax, t); //top
                self.style.top = t + "px";
                
                //是否为滚动条Y方向、
                if (Config.isScrollBar.bStatus && Config.isScrollBar.dir === 'y') { // 带滚动区域
                    scale = t / Config.yMax; //滚动比例 [0-1]
                    Config.sCon.style.top = -scale * (Config.sCon.offsetHeight - Config.sCon.parentNode.offsetHeight) + "px";
                }
                if(Config.callback) Config.callback(t);


            }

        }

        Config.scope.onmouseup = function() {
            this.onmousemove = null;
            this.onmouseup = null;
        }
        return false;


    }

}

